package com.bigdata.movieticketapi.handler;

import com.bigdata.movieticketapi.common.utils.DataResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

@RestControllerAdvice
public class RestResponseBodyAdviceHandler implements ResponseBodyAdvice<Object> {
    @Resource
    private ObjectMapper objectMapper;
    private final String stringConverter = "org.springframework.http.converter.StringHttpMessageConverter";
    /**
     * true:代表支持我们再响应数据给前端的时候做一些处理
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        return !returnType.getDeclaringClass().getName().contains("springfox");
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        /**
         * 当接口返回到类型消息转换器是StringHttpMessageConverter
         * 才需要把它转换成String
         */
        if(stringConverter.equalsIgnoreCase(selectedConverterType.getName())){
            HttpHeaders headers = response.getHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            return objectMapper.writeValueAsString(DataResult.success(body));
        }
        if(body instanceof DataResult){
            return body;
        }
        return DataResult.success(body);
    }
}
